import java.util.*;
import java.sql.*;
import java.awt.print.PrinterException;
import java.text.MessageFormat;
import java.util.Date;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;


public class SalesReport extends javax.swing.JFrame {

    /** Creates new form SalesReport */
    public SalesReport() {
        initComponents();
        jButton1.setEnabled(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel4 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        jComboBox7 = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jComboBox2 = new javax.swing.JComboBox();
        jComboBox3 = new javax.swing.JComboBox();
        jComboBox4 = new javax.swing.JComboBox();
        jComboBox5 = new javax.swing.JComboBox();
        jComboBox6 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Sales Report");

        jLabel1.setText("Sales Report");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Start Date", "End Date", "Total Sales", "Average Sales"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLabel4.setText("Intervals:");

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Weekly", "Monthly", "Yearly" }));

        jButton1.setText("Print");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Back");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Show Report");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel6.setText("Month - Day - Year");

        jComboBox7.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" }));
        jComboBox7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox7ActionPerformed(evt);
            }
        });

        jLabel2.setText("Start Date:");

        jLabel3.setText("End Date:");

        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" }));
        jComboBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox2ActionPerformed(evt);
            }
        });

        jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" }));

        jComboBox4.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "09", "10", "11", "12", "13", "14", "15", "16", "17", "18" }));
        jComboBox4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox4ActionPerformed(evt);
            }
        });

        jComboBox5.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "09", "10", "11", "12", "13", "14", "15", "16", "17", "18" }));
        jComboBox5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox5ActionPerformed(evt);
            }
        });

        jComboBox6.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(267, 267, 267)
                .addComponent(jLabel1)
                .addContainerGap(307, Short.MAX_VALUE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 635, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(78, 78, 78)
                            .addComponent(jLabel6))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel3)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jComboBox7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jComboBox6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jComboBox5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 281, Short.MAX_VALUE)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(149, 149, 149)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(106, 106, 106)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton1)
                            .addComponent(jButton2)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jLabel6)
                        .addGap(7, 7, 7)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jComboBox7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jComboBox6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jComboBox5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(55, 55, 55)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton3)
                            .addComponent(jLabel4)
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        ReportsProper x = new ReportsProper();
        x.show();
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed

        String interval = (String)jComboBox1.getSelectedItem();
        
               int sMonth = Integer.parseInt((String)jComboBox2.getSelectedItem());
               int sDay =Integer.parseInt((String)jComboBox3.getSelectedItem());
               int sYear = Integer.parseInt((String)jComboBox4.getSelectedItem());
              
               int eMonth = Integer.parseInt((String)jComboBox5.getSelectedItem());
               int eDay = Integer.parseInt((String)jComboBox6.getSelectedItem());
               int eYear = Integer.parseInt((String)jComboBox7.getSelectedItem());

               Date startDate = new Date(sYear + 100, sMonth-1, sDay);
               Date endDate = new Date(eYear + 100, eMonth-1, eDay);

               
               if(interval.compareToIgnoreCase("Weekly") == 0)
                 getWeekly(startDate, endDate);
               else if(interval.compareToIgnoreCase("Monthly") == 0)
                 getMonthly(startDate, endDate);
               else if(interval.compareToIgnoreCase("Yearly") == 0)
                 getYearly(startDate, endDate);
               jButton1.setEnabled(true);
           
      
      
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
         try {
          MessageFormat headerFormat = new MessageFormat("Sales Report");
          MessageFormat footerFormat = new MessageFormat("- {0} -");
          jTable1.print(JTable.PrintMode.FIT_WIDTH, headerFormat, footerFormat);
        } catch (PrinterException pe) {
          System.err.println("Error printing: " + pe.getMessage());
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jComboBox7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox7ActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_jComboBox7ActionPerformed

    private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox2ActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_jComboBox2ActionPerformed

    private void jComboBox4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox4ActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_jComboBox4ActionPerformed

    private void jComboBox5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox5ActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_jComboBox5ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SalesReport().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JComboBox jComboBox3;
    private javax.swing.JComboBox jComboBox4;
    private javax.swing.JComboBox jComboBox5;
    private javax.swing.JComboBox jComboBox6;
    private javax.swing.JComboBox jComboBox7;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables

   DB DB = new DB();
   int rowCount = 0;
   int type = 0;
   Connection conn;
   PreparedStatement pstmt;
   Statement stmt;
   ResultSet rset;
   String query;

     public void setValues(Vector row, int rowCount){
            Object z[] = {null,null,null,null};
            DefaultTableModel model = (javax.swing.table.DefaultTableModel)jTable1.getModel();
            jTable1.setModel(model);

            if(rowCount > 13){
                int q = rowCount - 13;
                for(int w = 0; w < q; w++){
                    model.addRow(z);
                }
            }

       		int columnNum = 0;
       		for(int i = 1; i <= rowCount; i++){
			for(columnNum = 0; columnNum < 4; columnNum++){
       		jTable1.setValueAt(row.elementAt(columnNum+(4*(i-1))), i-1, columnNum);}
       		columnNum = 0;}
     }

     public void clearValues(int rowCount){

       		int columnNum = 0;
       		for(int i = 1; i <= rowCount; i++){
			for(columnNum = 0; columnNum < 4; columnNum++){
       		jTable1.setValueAt("", i-1, columnNum);}
       		columnNum = 0;}
     }

     public void getWeekly(Date startDate, Date end){

            clearValues(rowCount);
            rowCount = 0;
            Date endDate = new Date();
            Vector row = new Vector();
            
            do{
            endDate = new Date(startDate.getYear(), startDate.getMonth(), startDate.getDate()+7);
            System.out.println(endDate);
            row.addElement(startDate);
            row.addElement(endDate);
            int sum = 0;

            try {
                       DB.connect();
                       conn = DB.getConn();

                       query = "select date, totalAmount from transaction where status = 1;";
                       pstmt = conn.prepareStatement(query);
                       rset = pstmt.executeQuery();


                       while(rset.next())
                       {
                             String date = rset.getString("date");
                             float amount = Float.valueOf(rset.getString("totalAmount"));

                             int month = Integer.parseInt(date.substring(0, 2));
                             int day = Integer.parseInt(date.substring(3, 5));
                             int year = Integer.parseInt(date.substring(6, 8));

                             Date tempDate = new Date(year +100, month-1, day);

                             if(tempDate.compareTo(startDate) >= 0 && tempDate.compareTo(endDate) <= 0)
                                sum += amount;
                       }

                       row.addElement(""+sum);
                       row.addElement(""+sum/7);
                       rowCount++;
                       setValues(row, rowCount);

                    DB.disconnect();
                    pstmt.close();

             } catch (Exception ex) {
                   System.out.println("aError: "+ex.getMessage());
             }

            startDate = endDate;
       }while(endDate.before(end));
     }

      public void getMonthly(Date startDate, Date end){

            clearValues(rowCount);
            rowCount = 0;
            Date endDate = new Date();
            Vector row = new Vector();

            do{
            endDate = new Date(startDate.getYear(), startDate.getMonth()+1, startDate.getDate());
            System.out.println(endDate);
            row.addElement(startDate);
            row.addElement(endDate);
            int sum = 0;

            try {
                       DB.connect();
                       conn = DB.getConn();

                       query = "select date, totalAmount from transaction where status = 1;";
                       pstmt = conn.prepareStatement(query);
                       rset = pstmt.executeQuery();


                       while(rset.next())
                       {
                             String date = rset.getString("date");
                             float amount = Float.valueOf(rset.getString("totalAmount"));

                             int month = Integer.parseInt(date.substring(0, 2));
                             int day = Integer.parseInt(date.substring(3, 5));
                             int year = Integer.parseInt(date.substring(6, 8));

                             Date tempDate = new Date(year +100, month-1, day);

                             if(tempDate.compareTo(startDate) >= 0 && tempDate.compareTo(endDate) <= 0)
                                sum += amount;
                       }

                       row.addElement(""+sum);
                       row.addElement(""+sum/30);
                       rowCount++;
                       setValues(row, rowCount);

                    DB.disconnect();
                    pstmt.close();

             } catch (Exception ex) {
                   System.out.println("bError: "+ex.getMessage());
             }

            startDate = endDate;
       }while(endDate.before(end));
     }

      public void getYearly(Date startDate, Date end){
          
            clearValues(rowCount);
            rowCount = 0;
            Date endDate = new Date();
            Vector row = new Vector();

            do{
            endDate = new Date(startDate.getYear()+1, startDate.getMonth(), startDate.getDate());
            System.out.println(endDate);
            row.addElement(startDate);
            row.addElement(endDate);
            int sum = 0;

            try {
                       DB.connect();
                       conn = DB.getConn();

                       query = "select date, totalAmount from transaction where status = 1;";
                       pstmt = conn.prepareStatement(query);
                       rset = pstmt.executeQuery();


                       while(rset.next())
                       {
                             String date = rset.getString("date");
                             float amount = Float.valueOf(rset.getString("totalAmount"));

                             int month = Integer.parseInt(date.substring(0, 2));
                             int day = Integer.parseInt(date.substring(3, 5));
                             int year = Integer.parseInt(date.substring(6, 8));

                             Date tempDate = new Date(year +100, month-1, day);

                             if(tempDate.compareTo(startDate) >= 0 && tempDate.compareTo(endDate) <= 0)
                                sum += amount;
                       }

                       row.addElement(""+sum);
                       row.addElement(""+sum/365);
                       rowCount++;
                       setValues(row, rowCount);

                    DB.disconnect();
                    pstmt.close();

             } catch (Exception ex) {
                   System.out.println("cError: "+ex.getMessage());
             }

            startDate = endDate;
       }while(endDate.before(end));
     }
}
